package com.seu.multithread.demo04;

import java.util.concurrent.CountDownLatch;

/**
 * @author liangfeihu
 * @since 2019/8/17
 */
public class ThreadPrintData2 {

    public static CountDownLatch latch = new CountDownLatch(2);

    private static Object lock = new Object();

    private static volatile Integer i = 0;
    private static final int TOTAL = 100;

    public static void main(String[] args) throws InterruptedException {

        long start = System.currentTimeMillis();
        Thread thread1 = new Thread() {

            @Override
            public void run() {
                while (i <= TOTAL) {
                    synchronized (lock) {
                        if (i % 2 == 1) {
                            if (i <= TOTAL) {
                                System.out.println(Thread.currentThread().getName() + "打印：   " + i++);
                            }
                        } else {
                            lock.notifyAll();
                            try {
                                if (i < TOTAL) {
                                    lock.wait();
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }

                latch.countDown();
            }
        };

        thread1.setName("奇数线程");
        Thread thread2 = new Thread() {

            @Override
            public void run() {
                while (i <= TOTAL) {
                    synchronized (lock) {
                        if (i % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + "打印：  " + i++);
                        } else {
                            lock.notifyAll();
                            try {
                                if (i < TOTAL) {
                                    lock.wait();
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
                latch.countDown();
            }
        };
        thread2.setName("偶数线程");

        thread1.start();
        thread2.start();

        latch.await();
        long end = System.currentTimeMillis();
        System.out.println("共耗时:" + (end - start) + "ms");
    }

}
